package com.openxt.nbzj.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.openxt.nbzj.R;
import com.openxt.nbzj.activity.EnterpriseCreditDetailsActivity;
import com.openxt.nbzj.adapter.EnterpriseCreditTypeListAdapter;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/7/7.
 */
public class EnterpriseCreditFragment extends OpenxtFragment implements AdapterView.OnItemClickListener, RemotingEx.OnActionListener {

    boolean isLoading = false;
    Handler mHandler = new Handler();
    JSONObject mItem = null;

    @BindView(R.id.ptrClassicFrameLayout)
    PtrClassicFrameLayout ptrClassicFrameLayout;
    @BindView(R.id.listView)
    ListView listView;

    private Context mContext = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    private int total = 0;
    private Long timeStamp = null;

    private List<JSONObject> mList = new ArrayList<>();
    private EnterpriseCreditTypeListAdapter enterpriseCreditTypeListAdapter = null;
    private RemotingModel remotingModel = null;

    private String nameId = null;
    public void setNameId(String nameId) {
        this.nameId = nameId;
    }
    public String getNameId() {
        return this.nameId;
    }

    public void setItem(JSONObject mItem) {
        this.mItem = mItem;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.enterprise_credit_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        remotingModel = new RemotingModel(mContext);
        enterpriseCreditTypeListAdapter = new EnterpriseCreditTypeListAdapter(mContext, mList);

        listView.setAdapter(enterpriseCreditTypeListAdapter);
        listView.setOnItemClickListener(this);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            pageIndex = 1;
                            timeStamp = null;
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                            doLoad();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            pageIndex++;
                            doLoadMore();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });
    }

    private void initData(){
        //获取缓存
        final String val = Utils.getLocalStorage(mContext, ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + nameId);
        if(!StringUtil.isNull(val)){
            mList.clear();
            enterpriseCreditTypeListAdapter.notifyDataSetChanged();
            try{
                JSONArray array = JSON.parseArray(val);
                for(int i = 0, j = array.size(); i < j; i++){
                    pageIndex = i + 1;
                    JSONObject item = array.getJSONObject(i);
                    JSONArray rows = item.getJSONArray("rows");
                    if(rows == null)
                        continue;
                    for(int m = 0, n = rows.size(); m < n; m++){
                        mList.add(rows.getJSONObject(m));
                    }

                    timeStamp = item.getLong("timeStamp");
                    total = item.getInteger("total");
                }
                enterpriseCreditTypeListAdapter.notifyDataSetChanged();

                if(total > (pageIndex * pageSize))
                    ptrClassicFrameLayout.setLoadMoreEnable(true);
                else
                    ptrClassicFrameLayout.setLoadMoreEnable(false);
                listView.setAdapter(enterpriseCreditTypeListAdapter);
            }catch (Exception e){
            }
        }else {
            if (ActivityUtil.isNetworkAvailable(mContext)) {
                ptrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ptrClassicFrameLayout.autoRefresh(true);
                    }
                }, 0);
            }
        }
    }

    private void doLoad(){
        try {
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("enttype", mItem.getString("ID"));
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            remotingModel.getEnterpriseGetPageNativeCredit(this, false, param, null);
        }catch (Exception e){

        }
    }

    private void doLoadMore(){
        try {
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("enttype", mItem.getString("ID"));
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            remotingModel.getEnterpriseGetPageNativeCredit(this, false, param, "$more");
        }catch (Exception e){

        }
    }

    @Override
    public void refresh() {
        if(isLoading)
            return;

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initData();
            }
        }, 100);

        isLoading = true;
    }

    @Override
    public void willBeDisplayed() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if (!ActivityUtil.isNetworkAvailable(mContext)) {
                showMsg("无网络，请先查看网络是否正常打开");
                return;
            }
            Bundle bundle = new Bundle();
            JSONObject item = mList.get(position);
            String ID = item.getString("ID");
            bundle.putString("ID", ID);
            toActivity(EnterpriseCreditDetailsActivity.class, bundle, false);
        }catch (Exception e){

        }
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        try {
             if (ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT.equals(actionName) || (ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + "$more").equals(actionName)) {
                if(pageIndex == 1)
                    Utils.removeLocalStorage(mContext, ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + nameId);
                JSONObject data = JSON.parseObject(reVal);
                final String val = Utils.getLocalStorage(mContext, ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + nameId);
                JSONArray cacheArray = null;
                if (StringUtil.isNull(val)) {
                    cacheArray = new JSONArray();
                    cacheArray.add(data);
                    Utils.setLocalStorage(mContext, ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + nameId, cacheArray.toString());
                } else {
                    cacheArray = JSON.parseArray(val);
                    if (cacheArray.size() < 5) {
                        cacheArray.add(data);
                        Utils.setLocalStorage(mContext, ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + nameId, cacheArray.toString());
                    }
                }
                total = data.getInteger("total");
                timeStamp = data.getLong("timeStamp");
                JSONArray rows = data.getJSONArray("rows");
                if (ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT.equals(actionName)) {
                    try {
                        mList.clear();
                        enterpriseCreditTypeListAdapter.notifyDataSetChanged();

                        for (int i = 0, j = rows.size(); i < j; i++) {
                            mList.add(rows.getJSONObject(i));
                        }
                        if (total > (pageIndex * pageSize))
                            ptrClassicFrameLayout.setLoadMoreEnable(true);
                        else
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                        listView.setAdapter(enterpriseCreditTypeListAdapter);
                    } finally {
                        ptrClassicFrameLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ptrClassicFrameLayout.refreshComplete();
                                enterpriseCreditTypeListAdapter.notifyDataSetChanged();
                            }
                        }, 0);
                    }
                }else if ((ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + "$more").equals(actionName)) {
                    try {
                        for (int i = 0, j = rows.size(); i < j; i++){
                            mList.add(rows.getJSONObject(i));
                        }
                        if(total > (pageIndex * pageSize))
                            ptrClassicFrameLayout.setLoadMoreEnable(true);
                        else
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                    } finally {
                        ptrClassicFrameLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if(total > (pageIndex * pageSize))
                                    ptrClassicFrameLayout.loadMoreComplete(true);
                                else
                                    ptrClassicFrameLayout.loadMoreComplete(false);
                                enterpriseCreditTypeListAdapter.notifyDataSetChanged();
                            }
                        }, 0);
                    }
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        if ((ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT + "$more").equals(actionName)){
            pageIndex--;
        }
        if(actionName.startsWith(ConfigModel.ENTERPRISE_GETPAGENATIVE_CREDIT)) {
            ptrClassicFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ptrClassicFrameLayout.refreshComplete();
                }
            }, 0);
        }
    }
}
